#ifndef _UDP_SERVER_HPP_
#define _UDP_SERVER_HPP_
#include <memory>
#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <strings.h>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Mutex.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "User.hpp"
#include "ThreadPool.hpp"

using namespace ThreadPoolModule;

using adduser_t = std::function<void(InetAddr &id)>;
using remove_t = std::function<void(InetAddr &id)>;
using route_t = std::function<void(int sockft, const std::string &message)>;
using task_t = std::function<void()>;

const static int gsockfd = -1;
const static std::string gdefaultip = "127.0.0.1";
const static uint16_t gdefaultport = 8080;

using namespace LogMudule;
using func_t = std::function<std::string(std::string &st)>;

class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gsockfd),
          _addr(port)

    {
    }

    void InitServer()
    {
        // 1.创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket:" << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success:";
        // 2.填充网络信息，并且进行绑定
        /*struct sockaddr_in local;
        bzero(&local, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = ::htons();    // 要被发送给对方的，即要发送到网络中
        local.sin_addr.s_addr = INADDR_ANY; // string ip->4bytes 2.network order*/

        // 2.1bind
        int n = ::bind(_sockfd, _addr.GetSockaddr_In(), _addr.LenSockaddr_in());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success:";
    }

    void RegisterService(adduser_t adduser, route_t route, remove_t removeuser)
    {
        _adduser = adduser;
        _route = route;
        _remover = removeuser;
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            // 收消息时，需要知道谁给我发的消息，利用socket标识另一端

            char inbuffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            /*InetAddr peer;//标识另一端
            socklen_t len = peer.LenSockaddr_in();*/
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len); // sockaddr_in peer会记录收到的ip和port
            if (n > 0)
            {
                // uint16_t peerport = ntohs(peer.sin_port);
                //  std::string peerip = ::inet_ntoa(peer.sin_addr);//network->4bytes->string ip
                // std::string peerip = ::inet_ntoa(peer.sin_addr); // network->4bytes->string ip
                
                //peer中的数据都是网络传输的数据，需要进行加工
                InetAddr cli(peer);
                inbuffer[n] = 0;

                std::string message;
                

                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    //std::cout<<"进来了QUIT"<<std::endl;
                    // 移除用户
                    _remover(cli);
                    message = cli.Addr() + "# " + "我走了，你们聊!";
                }
                else
                {
                    // 新增用户
                    _adduser(cli);
                    message = cli.Addr() + "# " + inbuffer;
                }

                // 将任务放入队列中，等待线程池执行
                // 上层将消息转发模块的对象方法封装起来，绑定两个参数后的对象方法，将方法放进线程池的任务队列中

                //显然此时的task_t是std::function<void()>;类型的，将Route接口的两个参数进行了绑定
                task_t task = std::bind(_route, _sockfd, message); //_route是一个回调方法不是成员方法
                ThreadPool<task_t>::getInstance()->Equeue(task);

                /*std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port()) + "#" + inbuffer;
                LOG(LogLevel::DEBUG) << clientinfo;
                std::string Message = "echo# ";
                Message += inbuffer;

                ::sendto(_sockfd, Message.c_str(), Message.size(), 0, CONV(&peer), len);*/
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

private:
    int _sockfd;
    InetAddr _addr;
    // uint16_t _port; // 服务器未来的端口号
    //  std::string _ip;
    bool _isrunning = false;
    // func_t _func;
    remove_t _remover;
    adduser_t _adduser;
    route_t _route;
    task_t task;
};

#endif